package com.baobaotao.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import com.baobaotao.domain.User;

@Repository //通过Spring注解定义一个DAO
public class UserDao {
	
	protected Log logger = LogFactory.getLog(getClass());
	
	@Autowired //自动注入JdbcTemplate的Bean
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 根据用户名和密码获取匹配的用户数
	 * */
	public int getMatchCount(String userName,String password){
		logger.info("Calling getMatchCount, " + userName+","+password);
		String sql = "SELECT COUNT(1) FROM T_USER WHERE USER_NAME = ? AND PASSWORD = ? ";
		return jdbcTemplate.queryForInt(sql,new Object[]{userName,password});
	}
	/**根据用户名称找到用户*/
	public User findUserByUserName(final String userName){
		String sql = "SELECT USER_ID,USER_NAME,CREDITS FROM T_USER WHERE USER_NAME = ? ";
		final User user = new User();
		jdbcTemplate.query(sql, new Object[]{userName},new RowCallbackHandler() {
			
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				// TODO Auto-generated method stub
				user.setUserId(rs.getInt("USER_ID"));
				user.setUserName(userName);
				user.setCredits(rs.getInt("CREDITS"));
			}
		});
		return user;
	}
	/**更新用户的登陆信息*/
	public void updateLoginInfo(User user){
		String sql = "UPDATE T_USER SET LAST_VISIT=?,LAST_IP = ?,CREDITS = ? WHERE USER_ID = ? ";
		jdbcTemplate.update(sql,new Object[]{user.getLastVisit(),
				user.getLastIp(),user.getCredits(),user.getUserId()});
	}
}
